package com.example.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.example.model.User;
import com.example.service.UserService;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    // 创建一个 UserService 实例，通常在实际项目中会使用依赖注入
    private UserService userService = new UserService();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1. 设置请求编码，防止中文乱码
        request.setCharacterEncoding("UTF-8");

        // 2. 获取用户从登录页面提交的参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 3. 将参数封装到Model(JavaBean)对象中
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        // 4. 调用Service层处理业务逻辑
        boolean loginSuccess = userService.validateUser(user);

        // 5. 根据处理结果，准备数据并决定跳转到哪个View(JSP)
        if (loginSuccess) {
            // 登录成功
            // 使用Session来保存用户登录状态
            HttpSession session = request.getSession();
            session.setAttribute("loggedInUser", user);
            
            // 重定向到欢迎页面
            response.sendRedirect("welcome.jsp");
        } else {
            // 登录失败
            // 将错误信息存入request作用域
            request.setAttribute("errorMessage", "用户名或密码错误！");
            
            // 转发回登录页面，并显示错误信息
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }
}